// 引入 axios
import axios from 'axios';

// cp是全局变量，之前是通过使用process.env.NODE_ENV==='production'来判断打包的是哪一个路径，在tomcat下是..(由于在Tomcat是domain在obpm里面，但是要找到根目录的路径)，在本地是obpm
const obpmFilePath = obpmConfig.obpmFilePath
const contextPath = obpmConfig.contextPath; 
const magicAppName = obpmConfig.magicAppName
const appId = obpmConfig.appId
const webuserid = '__oP0irhWXGA2oZRusW1d' || top.trunkVariable.user.id //'__oP0irhWXGA2oZRusW1d' || 
console.log(top.trunkVariable,'top.trunkVariable')
const instance = axios.create({
});
instance.interceptors.request.use(
    config => {
        if(config.method.toLowerCase() == 'put' || config.method.toLowerCase() == 'post'){
            // config.headers['adminToken'] = localStorage.getItem('adminToken');
            // if(config.data && config.data.loginpwd && config.data.loginpwd.length > 60){
            //     Message.error('密码长度不能大于60位')
            //     return false
            // }
            return config
        }else{
            // config.headers['adminToken'] = localStorage.getItem('adminToken');
            return config
        }
    },
    err => {
        return Promise.reject(err)
    }
);

//http response 拦截器
instance.interceptors.response.use(
    response => {
        console.log("axios.interceptors.response");
        return response;
    },
    error => {
        //未登录
        if (error.response.status == 401) {
            window.location = "index.html#/login";
        }
        else {
            return Promise.reject(error)
        }
    }
);

instance.defaults.withCredentials = true;

/**
 * 项目管理
 */

///runtime/upload?applicationId={applicationId}&allowedTypes={allowedTypes}&fieldId={fieldId}&fileSaveMode={fileSaveMode}&path={path}&actionType={actionType}
export function uploadFile(files, appId, allowedTypes, fieldId, fileSaveMode, path, actionType, sourceFileId,docId,{ onSucess, onError }, callback1, uid) {
    let accessToken = localStorage.getItem('accessToken')
    axios({
        headers: {
            "content-type": "multipart/form-data;boundary=" + Math.random(),
            "accessToken" : accessToken
        },
        data: files,
        url: contextPath + "/runtime/upload?applicationId=" +
            appId +
            "&allowedTypes=" +
            allowedTypes +
            "&fieldId=" +
            fieldId +
            "&fileSaveMode=" +
            fileSaveMode +
            "&path=" +
            path +
            "&actionType=" +
            actionType +
            "&sourceFileId=" +
            sourceFileId +
            "&docId=" +
            docId,
        method: "post",
        onUploadProgress:(progressEvent) => { 
            let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%';
            let num =  (progressEvent.loaded / progressEvent.total * 100 | 0);
            let obj = {
                complete: complete,
                num: num,
                uid: uid,
            }
            callback1(obj);
        }
    }).then(function (response) {
        if(onSucess) onSucess(response);
    }).catch(
        function (error) {
            if(onError) onError(error);
        }
    )  
}
/**
 * 通过文件路径和名称判断是否存在对应的PDF文件
 */
export function getHasPdfFile (filePath, fileRealName, { onSucess, onError }) {
    filePath = encodeURI(filePath).replace(/#/g,'%23').replace(/\+/g,'%2B')
    fileRealName = encodeURI(fileRealName).replace(/#/g,'%23').replace(/\+/g,'%2B')
    instance.get(contextPath + '/runtime/files/hasPdf?path=' + filePath + '&fileRealName=' + fileRealName).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
/**
 * 获取是否配置文件预览环境的信息
 */
export function getenvironment ({ onSucess, onError }) {
    instance.get(contextPath + '/runtime/files/preview/environment').then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
//获取视图列
export function getViewTemplate (viewId, { onSucess, onError }) {
    instance.get(contextPath + '/runtime/' + appId + '/views/' + viewId + '/template',).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
//查询表单
export function getSearchFormTemplate (viewId, exparams, { onSucess, onError }) {
    instance.get(contextPath + '/runtime/' + appId + '/views/' + viewId + '/searchformtemplate', {params:exparams}).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
/**
 * 获取视图数据
 */
export function getViewData (viewId, params, data, { onSucess, onError }) {
    let urlParams = '';
    let parentId = params.parentId ? params.parentId : '';
    let sortCol = params.sortCol ? params.sortCol : '';
    let sortStatus = params.sortStatus ? params.sortStatus : '';
    let currpage = params.currpage ? params.currpage : '1';
    let lines = params.lines ? params.lines : '';
    let treedocid = params.treedocid ? params.treedocid : '';
    let parentNodeId = params.parentNodeId ? params.parentNodeId : '';
    let docid = params.docid ? params.docid : '';
    let fieldid = params.fieldid ? params.fieldid : '';
    let isRelate = params.isRelate ? params.isRelate : '';
    let startDate = params.startDate ? params.startDate : '';
    let endDate = params.endDate ? params.endDate : '';
    let exparams = params.exparams ? params.exparams : '';
    let parentParam = params.parentParam ? params.parentParam : '';
    let Execution_Time = params.Execution_Time ? params.Execution_Time : '';

    urlParams += 
        '?parentId=' + parentId + 
        '&sortCol=' + sortCol +
        '&sortStatus=' + sortStatus + 
        '&_currpage=' + currpage +
        '&lines=' + lines + 
        '&treedocid=' + treedocid +
        '&parentNodeId=' + parentNodeId + 
        '&_docid=' + docid +
        '&_fieldid=' + fieldid + 
        '&isRelate=' + isRelate +
        '&startDate=' + startDate + 
        '&endDate=' + endDate + 
        '&parentParam=' + parentParam+
        '&Execution_Time='+Execution_Time
    if (data && exparams) {
        data = Object.assign(data, exparams);
    }
    instance.post(contextPath + '/runtime/' + appId + '/views/' + viewId + '/documents' + urlParams, data ? data : {}).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
export function getProjectTemplateList(userId,{ onSucess, onError }) {
    instance.get(obpmFilePath + '/magic-api/'+magicAppName+'/project_template_list?userId='+userId).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
/**
 * 2.10	批量删除文档
 * 请求方式：DELETE
 * 请求地址：/runtime/{applicationId}/documents
 */
export function batchRemoveDocuments (idsArray, { onSucess, onError }) {
    instance.delete(contextPath + '/runtime/' + appId + '/documents', {data: idsArray}).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
export function getAxecuteAddress(actId, jsonData, {onSucess, onError}) {
    let isRelate = jsonData.isRelate ? jsonData.isRelate : ''
    let parentId = jsonData.parentId ? jsonData.parentId : ''
    let treedocid = jsonData.treedocid ? jsonData.treedocid : ''
    instance.put(contextPath + "/runtime/" + appId + "/activities/" + actId + "/executeAddress?isRelate=" + isRelate + "&parentId=" + parentId + "&treedocid=" + treedocid,jsonData).then(function(response){
         if(onSucess) onSucess(response);
     }).catch(function(error) {
         if(onError) onError(error);
     })   
}
export function customStage({ onSucess, onError }) {
    instance.get(obpmFilePath + '/magic-api/'+magicAppName+'/customStage').then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
//CRM
//阶段及任务获取
export function getStage(type,docid,{ onSucess, onError }) {
    instance.get(obpmFilePath + '/magic-api/'+magicAppName+'/stage?type='+type+"&docid="+docid + "&webuserid="+webuserid).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
/**
 * 获取表单
 */
export function getForm (appId, formId, docId, exparams, { onSucess, onError }) {
    let url = contextPath + '/runtime/' + appId + '/forms/' + formId + '/documents/' + docId
    instance({
        url: url,
        method: 'get',
        params: exparams ? exparams : {},
    }).then(function(response){
        if(onSucess) onSucess(response);
    }).catch(function(error) {
        if(onError) onError(error);
    })
}
//跳转按钮获取地址
export function runScript (appId, actId, docId, fieldName, _, subSelectId,{ onSucess, onError }) {
    let url = contextPath + '/runtime/' + appId + '/activities/' + actId + '/runScript?docId=' + docId + '&fieldName=' + fieldName + "&_" + _
    if(subSelectId) {
        url += "&subSelects=" + subSelectId
    }
    instance.get(url).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
//动态信息获取
export function getDynamic(type,docid,{ onSucess, onError }) {
    instance.get(obpmFilePath + '/magic-api/'+magicAppName+'/dynamic?type='+type+"&docid="+docid+ "&webuserid="+webuserid).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
//跟进记录点赞
export function upvote(docid,{ onSucess, onError }) {
    instance.get(obpmFilePath + '/magic-api/'+magicAppName+'/upvote?docid='+docid+"&webuserid="+webuserid).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
//获取回复记录
export function getreply(docid,{ onSucess, onError }) {
    instance.get(obpmFilePath + '/magic-api/'+magicAppName+'/getreply?docid='+docid).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
//跟进记录回复
export function reply(docid,data,{ onSucess, onError }) {
    instance.post(obpmFilePath + '/magic-api/'+magicAppName+'/reply?docid='+docid + '&webuserid='+webuserid,data).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}
//改变状态
export function updatePlan(docid,{ onSucess, onError }) {
    instance.get(obpmFilePath + '/magic-api/'+magicAppName+'/updatePlan?docid='+docid).then(function (response) {
        if (onSucess) onSucess(response);
    }).catch(
        function (error) {
            if (onError) onError(error);
        }
    );
}

